package com.zaimokuza.cn.config.security;

import com.zaimokuza.cn.entity.user.LoginUser;
import com.zaimokuza.cn.entity.user.SecurityUser;
import com.zaimokuza.cn.service.UserService;
import com.zaimokuza.cn.util.HttpUtils;
import com.zaimokuza.cn.util.grace.GraceResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功处理
 *
 * @author zaimokuza
 */
@Component
public class CustomizeAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private UserService userService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 获取对象信息
        SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
        // 添加登录记录
        userService.saveLoginRecord(securityUser.getId());
        // 查询用户登录信息
        LoginUser userLoginInfo = userService.getUserLoginInfo(securityUser.getId());
        // 添加到响应信息中返回
        HttpUtils.response(response, GraceResponse.success(userLoginInfo));
    }

}
